package com.heima.wemedia.filiter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wmUser.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
@Slf4j
@Order(1)
@WebFilter(filterName = "WmTokenFilter", urlPatterns = "/*")
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求头中的userId的信息
        String userId = request.getHeader("userId");
        //判断userId是否为空
        if (StringUtils.isNotBlank(userId)) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            //将该用户封装到线程中去
            WmThreadLocalUtils.setUser(wmUser);
        }
        //放行
        filterChain.doFilter(request, response);
        //清理当前线程
        WmThreadLocalUtils.clear();
    }
}
